<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\Message\Repository;

use Plugin\Message\Model\Message;
use Hyperf\Database\Model\Builder;
use App\Repository\IRepository;
use Hyperf\Collection\Arr;

/**
 * 消息表 Repository类
 */
class MessageRepository extends IRepository
{
   public function __construct(
        protected readonly Message $model
    ) {}

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        
        // 消息ID
        if (isset($params['id']) && filled($params['id'])) {
            $query->whereIn('id', Arr::wrap($params['id']));
        }

        // 消息类型1预警2反馈3系统
        if (isset($params['type']) && filled($params['type'])) {
            $query->where('type', '=', $params['type']);
        }

        // 消息标题
        if (isset($params['title']) && filled($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }

        // 消息内容
        if (isset($params['content']) && filled($params['content'])) {
            $query->where('content', 'like', '%' . $params['content'] . '%');
        }

        // 关联ID
        if (isset($params['related_id']) && filled($params['related_id'])) {
            $query->where('related_id', '=', $params['related_id']);
        }

        // 消息级别1普通2重要3紧急
        if (isset($params['level']) && filled($params['level'])) {
            $query->where('level', '=', $params['level']);
        }

        // 创建时间范围
        if (isset($params['created_at']) && filled($params['created_at']) && is_array($params['created_at']) && count($params['created_at']) == 2) {
            $query->whereBetween(
                'created_at',
                [ $params['created_at'][0], $params['created_at'][1] ]
            );
        }

        // 更新时间范围
        if (isset($params['updated_at']) && filled($params['updated_at']) && is_array($params['updated_at']) && count($params['updated_at']) == 2) {
            $query->whereBetween(
                'updated_at',
                [ $params['updated_at'][0], $params['updated_at'][1] ]
            );
        }

        return $query;
    }


}